from django.shortcuts import render
from . import models
from PIL import Image
from django.http import HttpResponseRedirect
import os
import numpy as np
from keras.applications.vgg16 import VGG16
from keras.applications.vgg16 import preprocess_input as preprocess_input_vgg
from keras.preprocessing import image
from numpy import linalg as LA
import os,h5py
import matplotlib.image as mpimg
import matplotlib.pyplot as plt
import numpy as np

#hash算法，识别率较低
def Get_hash(image_path):
    im = Image.open(image_path)
    im = im.resize((8, 8), Image.ANTIALIAS).convert('L')  # 将图片缩小到8x8，并改成灰度模式
    avg = sum(list(im.getdata())) / 64.0  # 得到像素平均值
    str = ''.join(map(lambda i: '0' if i < avg else '1', im.getdata()))  # 得到哈希字符串
    str = ''.join(map(lambda x: '%x' % int(str[x: x + 4], 2), range(0, 64, 4)))  # %x：转换无符号十六进制
    return str
def Get_Hamming(img1, img):

    Hamming = 0
    for i in range(16):
        if img1[i] != img[i]:
            Hamming += 1
    return Hamming

#深度学习算法，较深
class VGGNet():
    def __init__(self):
        self.input_shape=(224,224,3)
        self.weight='imagenet'
        self.pooling='max'
        self.model_vgg=VGG16(weights=self.weight,
                             input_shape=(self.input_shape[0],self.input_shape[1],self.input_shape[2]),
                             pooling=self.pooling,include_top=False
                             )
        self.model_vgg.predict(np.zeros((1,224,224,3)))

    def vgg_extract_feat(self,img_path):
        img=image.load_img(img_path,target_size=(self.input_shape[0],self.input_shape[1]))
        img=image.img_to_array(img)
        img=np.expand_dims(img,axis=0)
        img=preprocess_input_vgg(img)
        feat=self.model_vgg.predict(img)
        norm_feat=feat[0] / LA.norm(feat[0])
        return  norm_feat

# def get_imlist(path):
#     return [os.path.join(path, f) for f in os.listdir(path) if f.endswith('.png') or f.endswith('.jpg')]


# print(get_imlist("../media/images/20211123/"))

def img_new(request):
    index='media/1.h5'
    img_all=models.img.objects.all()
    img_list=[]
    for c in img_all:
        img_list.append(c.image.path)
    print ("--------------------------")
    feats=[]
    names=[]
    model=VGGNet()
    for i,image_path in enumerate(img_list):
        norm_feat=model.vgg_extract_feat(image_path)
        print(norm_feat)
        print("开始：%s"%image_path)
        img_name=image_path
        # img_name=os.path.split(image_path)[1]
        feats.append(norm_feat)
        names.append(img_name.encode())
        print ("extractingg feature from image No")

    feats=np.array(feats)
    output=index
    h5f=h5py.File(output,'w')
    h5f.create_dataset('dataset_1',data=feats)
    h5f.create_dataset('dataset_2',data=np.string_(names))
    h5f.close()
    return HttpResponseRedirect("/imggao")


def img_gao(request):
    imgdata=models.img.objects.all()
    title="深度学习"
    return  render(request,'gao.html',{'tit':title,'img':imgdata})


#点解图片排序深度学习识别
def ss(request):
    index="media/1.h5"
    h5f=h5py.File(index,'r')
    feats=h5f['dataset_1'][:]
    imgNames=h5f['dataset_2'][:]
    h5f.close()
    name =  request.GET['id']
    img=models.img.objects.filter(id=name)
    query=img[0].image.path #提交的图片
    print(query)
    model=VGGNet()
    queryVec=model.vgg_extract_feat(query)
    scores=np.dot(queryVec,feats.T)
    rank_ID=np.argsort(scores)[::-1]
    rank_score=scores[rank_ID]
    maxres=10#获取的张数
    imlist=[]
    for i,index in enumerate(rank_ID[0:20]):
        imlist.append(imgNames[index])
    imglist=[]
    for i,im in enumerate(imlist):
        aaaa=(str(im).split("\\media\\"))
        imgpath=(aaaa[1].replace("'","").replace(r"\\","/")[1:])#将识别的信息路径格式化成数据一样
        print(222222222222222222,imgpath)
        imgg=models.img.objects.filter(image=imgpath)
        print (imgg)
        try:
            imglist.append(imgg[0])
        except:
            print("出错：%s"%imgpath)
    return render(request,'gao.html',{'img':imglist})


def index(request):
    title="以图搜图"
    imgdata=models.img.objects.all()
    return  render(request,'index.html',{'tit':title,'img':imgdata})


#点解图片排序哈希
def sou(request):
     name =  request.GET['id']
     imglist=models.img.objects.all()
     img=models.img.objects.filter(id=name)
     imgdata1=img[0].img_data
     imglll={}
     for c in imglist:
            num=Get_Hamming(c.img_data,imgdata1)
            aa={}
            imglll[c.id]=num
     netdit=(sorted(imglll.items(), key=lambda item:item[1]))
     newdit=[]
     for i in netdit:
         aa=models.img.objects.filter(id=i[0])
         newdit.append(aa[0])
     return render(request,'index.html',{'img':newdit})


def start(reuqest):
    imgdata=models.img.objects.all()
    for c in imgdata:
        print(c)
        imgpath=c.image
        hashdata=Get_hash(imgpath)
        models.img.objects.filter(image=imgpath).update(img_data=hashdata)
    title="提交"
    return  HttpResponseRedirect("/")
# Create your views here.


def uploads_files(request):
    if request.method == 'POST':
        files = request.FILES.getlist('file_field')
        for f in files:
            file = models.img(img_path=f,img_tag='1',img_data="1",image=f)
            file.save()
    title="搜图"
    return  HttpResponseRedirect("/")